package com.yonglian.management.web.rest;

import static com.yonglian.management.domain.ActivityStandardAsserts.*;
import static com.yonglian.management.web.rest.TestUtil.createUpdateProxyForBean;
import static com.yonglian.management.web.rest.TestUtil.sameInstant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonglian.management.IntegrationTest;
import com.yonglian.management.domain.ActivityStandard;
import com.yonglian.management.repository.ActivityStandardRepository;
import jakarta.persistence.EntityManager;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

/**
 * Integration tests for the {@link ActivityStandardResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class ActivityStandardResourceIT {

    private static final String DEFAULT_STANDARD_NAME = "AAAAAAAAAA";
    private static final String UPDATED_STANDARD_NAME = "BBBBBBBBBB";

    private static final ZonedDateTime DEFAULT_CREATE_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    private static final ZonedDateTime UPDATED_CREATE_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);

    private static final String ENTITY_API_URL = "/api/activity-standards";
    private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";

    private static Random random = new Random();
    private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));

    @Autowired
    private ObjectMapper om;

    @Autowired
    private ActivityStandardRepository activityStandardRepository;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restActivityStandardMockMvc;

    private ActivityStandard activityStandard;

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static ActivityStandard createEntity(EntityManager em) {
        ActivityStandard activityStandard = new ActivityStandard().standardName(DEFAULT_STANDARD_NAME).createTime(DEFAULT_CREATE_TIME);
        return activityStandard;
    }

    /**
     * Create an updated entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static ActivityStandard createUpdatedEntity(EntityManager em) {
        ActivityStandard activityStandard = new ActivityStandard().standardName(UPDATED_STANDARD_NAME).createTime(UPDATED_CREATE_TIME);
        return activityStandard;
    }

    @BeforeEach
    public void initTest() {
        activityStandard = createEntity(em);
    }

    @Test
    @Transactional
    void createActivityStandard() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the ActivityStandard
        var returnedActivityStandard = om.readValue(
            restActivityStandardMockMvc
                .perform(
                    post(ENTITY_API_URL)
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(om.writeValueAsBytes(activityStandard))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            ActivityStandard.class
        );

        // Validate the ActivityStandard in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        assertActivityStandardUpdatableFieldsEquals(returnedActivityStandard, getPersistedActivityStandard(returnedActivityStandard));
    }

    @Test
    @Transactional
    void createActivityStandardWithExistingId() throws Exception {
        // Create the ActivityStandard with an existing ID
        activityStandard.setId(1L);

        long databaseSizeBeforeCreate = getRepositoryCount();

        // An entity with an existing ID cannot be created, so this API call must fail
        restActivityStandardMockMvc
            .perform(
                post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityStandard))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityStandard in the database
        assertSameRepositoryCount(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    void checkStandardNameIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        activityStandard.setStandardName(null);

        // Create the ActivityStandard, which fails.

        restActivityStandardMockMvc
            .perform(
                post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityStandard))
            )
            .andExpect(status().isBadRequest());

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllActivityStandards() throws Exception {
        // Initialize the database
        activityStandardRepository.saveAndFlush(activityStandard);

        // Get all the activityStandardList
        restActivityStandardMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(activityStandard.getId().intValue())))
            .andExpect(jsonPath("$.[*].standardName").value(hasItem(DEFAULT_STANDARD_NAME)))
            .andExpect(jsonPath("$.[*].createTime").value(hasItem(sameInstant(DEFAULT_CREATE_TIME))));
    }

    @Test
    @Transactional
    void getActivityStandard() throws Exception {
        // Initialize the database
        activityStandardRepository.saveAndFlush(activityStandard);

        // Get the activityStandard
        restActivityStandardMockMvc
            .perform(get(ENTITY_API_URL_ID, activityStandard.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(activityStandard.getId().intValue()))
            .andExpect(jsonPath("$.standardName").value(DEFAULT_STANDARD_NAME))
            .andExpect(jsonPath("$.createTime").value(sameInstant(DEFAULT_CREATE_TIME)));
    }

    @Test
    @Transactional
    void getNonExistingActivityStandard() throws Exception {
        // Get the activityStandard
        restActivityStandardMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    void putExistingActivityStandard() throws Exception {
        // Initialize the database
        activityStandardRepository.saveAndFlush(activityStandard);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the activityStandard
        ActivityStandard updatedActivityStandard = activityStandardRepository.findById(activityStandard.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedActivityStandard are not directly saved in db
        em.detach(updatedActivityStandard);
        updatedActivityStandard.standardName(UPDATED_STANDARD_NAME).createTime(UPDATED_CREATE_TIME);

        restActivityStandardMockMvc
            .perform(
                put(ENTITY_API_URL_ID, updatedActivityStandard.getId())
                    .with(csrf())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(om.writeValueAsBytes(updatedActivityStandard))
            )
            .andExpect(status().isOk());

        // Validate the ActivityStandard in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedActivityStandardToMatchAllProperties(updatedActivityStandard);
    }

    @Test
    @Transactional
    void putNonExistingActivityStandard() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityStandard.setId(longCount.incrementAndGet());

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restActivityStandardMockMvc
            .perform(
                put(ENTITY_API_URL_ID, activityStandard.getId())
                    .with(csrf())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(om.writeValueAsBytes(activityStandard))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityStandard in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithIdMismatchActivityStandard() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityStandard.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restActivityStandardMockMvc
            .perform(
                put(ENTITY_API_URL_ID, longCount.incrementAndGet())
                    .with(csrf())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(om.writeValueAsBytes(activityStandard))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityStandard in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithMissingIdPathParamActivityStandard() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityStandard.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restActivityStandardMockMvc
            .perform(
                put(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityStandard))
            )
            .andExpect(status().isMethodNotAllowed());

        // Validate the ActivityStandard in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void partialUpdateActivityStandardWithPatch() throws Exception {
        // Initialize the database
        activityStandardRepository.saveAndFlush(activityStandard);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the activityStandard using partial update
        ActivityStandard partialUpdatedActivityStandard = new ActivityStandard();
        partialUpdatedActivityStandard.setId(activityStandard.getId());

        partialUpdatedActivityStandard.createTime(UPDATED_CREATE_TIME);

        restActivityStandardMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedActivityStandard.getId())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(partialUpdatedActivityStandard))
            )
            .andExpect(status().isOk());

        // Validate the ActivityStandard in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertActivityStandardUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedActivityStandard, activityStandard),
            getPersistedActivityStandard(activityStandard)
        );
    }

    @Test
    @Transactional
    void fullUpdateActivityStandardWithPatch() throws Exception {
        // Initialize the database
        activityStandardRepository.saveAndFlush(activityStandard);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the activityStandard using partial update
        ActivityStandard partialUpdatedActivityStandard = new ActivityStandard();
        partialUpdatedActivityStandard.setId(activityStandard.getId());

        partialUpdatedActivityStandard.standardName(UPDATED_STANDARD_NAME).createTime(UPDATED_CREATE_TIME);

        restActivityStandardMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedActivityStandard.getId())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(partialUpdatedActivityStandard))
            )
            .andExpect(status().isOk());

        // Validate the ActivityStandard in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertActivityStandardUpdatableFieldsEquals(
            partialUpdatedActivityStandard,
            getPersistedActivityStandard(partialUpdatedActivityStandard)
        );
    }

    @Test
    @Transactional
    void patchNonExistingActivityStandard() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityStandard.setId(longCount.incrementAndGet());

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restActivityStandardMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, activityStandard.getId())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(activityStandard))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityStandard in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithIdMismatchActivityStandard() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityStandard.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restActivityStandardMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, longCount.incrementAndGet())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(activityStandard))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityStandard in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithMissingIdPathParamActivityStandard() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityStandard.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restActivityStandardMockMvc
            .perform(
                patch(ENTITY_API_URL)
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(activityStandard))
            )
            .andExpect(status().isMethodNotAllowed());

        // Validate the ActivityStandard in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void deleteActivityStandard() throws Exception {
        // Initialize the database
        activityStandardRepository.saveAndFlush(activityStandard);

        long databaseSizeBeforeDelete = getRepositoryCount();

        // Delete the activityStandard
        restActivityStandardMockMvc
            .perform(delete(ENTITY_API_URL_ID, activityStandard.getId()).with(csrf()).accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());

        // Validate the database contains one less item
        assertDecrementedRepositoryCount(databaseSizeBeforeDelete);
    }

    protected long getRepositoryCount() {
        return activityStandardRepository.count();
    }

    protected void assertIncrementedRepositoryCount(long countBefore) {
        assertThat(countBefore + 1).isEqualTo(getRepositoryCount());
    }

    protected void assertDecrementedRepositoryCount(long countBefore) {
        assertThat(countBefore - 1).isEqualTo(getRepositoryCount());
    }

    protected void assertSameRepositoryCount(long countBefore) {
        assertThat(countBefore).isEqualTo(getRepositoryCount());
    }

    protected ActivityStandard getPersistedActivityStandard(ActivityStandard activityStandard) {
        return activityStandardRepository.findById(activityStandard.getId()).orElseThrow();
    }

    protected void assertPersistedActivityStandardToMatchAllProperties(ActivityStandard expectedActivityStandard) {
        assertActivityStandardAllPropertiesEquals(expectedActivityStandard, getPersistedActivityStandard(expectedActivityStandard));
    }

    protected void assertPersistedActivityStandardToMatchUpdatableProperties(ActivityStandard expectedActivityStandard) {
        assertActivityStandardAllUpdatablePropertiesEquals(
            expectedActivityStandard,
            getPersistedActivityStandard(expectedActivityStandard)
        );
    }
}
